<template>
    <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" v-loading="formLoading">
        <el-form-item label="用户名" prop="username">
            <el-input v-model="form.username" clearable />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
            <el-input v-model="form.nickname" clearable />
        </el-form-item>
        <el-form-item v-if="!isEdit" label="密码" prop="password">
            <el-input type="password" v-model="form.password" show-password />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submit" :loading="loading">确定</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup lang="ts" name="AddOrEditUser">
import { ref, reactive, onMounted } from 'vue';
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus';
import type { UserType } from '@/api/user/types';
import { userCreateOrEdit, userGetById } from '@/api/user';
import CryptoJS from 'crypto-js'

const props = defineProps(['isEdit', 'id'])
const emit = defineEmits(['editSuccess'])

const loading = ref(false)
const formLoading = ref(false)
let form = reactive<UserType>({ username: '', nickname: '', password: '' })
const formRef = ref<FormInstance>()

// 校验规则
const rules = reactive<FormRules<UserType>>({
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
})

onMounted(() => {
    if (props.isEdit) {
        loadUser()
    }
})

const loadUser = async () => {
    formLoading.value = true
    const data = await userGetById(props.id)
    // Object.assign(form, data.data)
    const { id, username, nickname } = data.data
    Object.assign(form, { id, username, nickname })
    formLoading.value = false
}
const submit = async () => {
    await formRef.value?.validate()
    try {
        loading.value = true
        //const data = await userCreateOrEdit(form)
        const { password, ...rest } = form
        const cryptoPassword = CryptoJS.SHA256(password as string).toString()
        const data = await userCreateOrEdit(password === "" ? { ...rest } : { password: cryptoPassword, ...rest })
        if (data.code === 200) {
            ElMessage.success(props.isEdit ? '修改成功' : '添加成功')
            emit('editSuccess')
        }
    } finally {
        loading.value = false
    }
}
</script>

<style scoped lang="scss"></style>
